//
//  NetWorkingTools.swift
//  SinaWeibo
//
//  Created by apple on 15/11/17.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import AFNetworking

//在开发中会有两个环境 一个测试 一个线上 所以定义俩个接口 

//线上环境
let hostName = "https://api.weibo.com/"


//测试环境
let testName = "https://www.baidu.com"

//定义一个网络访问方法的枚举
enum HTTPMethod : String {
    
    case GET = "GET"
    case POST = "POST"
}

private let  errorDomain = "com.baidu.data.error"

class NetWorkingTools: AFHTTPSessionManager {

    //定义单例对象
    static let shareTools :NetWorkingTools = {
      
        let url = NSURL(string: hostName)
        
        let tools = NetWorkingTools(baseURL: url)
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
        
    }()
    
    //提供一个外界可以访问网络的接口
    func requestJSONDict(method:HTTPMethod,urlString:String,parameters:[String:AnyObject],finished:(result:[String:AnyObject]? ,error:NSError?)->()){
        
        if method == HTTPMethod.GET {
            
            GET(urlString, parameters: parameters, success: { (_, result) -> Void in
                
                //检验数据是否是字典
                if let dict = result as? [String:AnyObject] {
                    
                    //执行成功的回调
                    finished(result: dict, error: nil)
                    
                    return
                }
                
                //自定义一个网络错误
                //code 一般为负值
                let dataError = NSError(domain: errorDomain, code: -100, userInfo: [NSLocalizedDescriptionKey:"数据饿格式错误"])
                
                finished(result: nil, error: dataError)

                
                }) { (_, error) -> Void in
                    //执行错误的回调
                    finished(result: nil, error: error)
                    print(error)
            }
            

        }
        if method == HTTPMethod.POST {
            
            
            POST(urlString, parameters: parameters, success: { (_, result) -> Void in
                
                //检验数据是否是字典
                if let dict = result as? [String:AnyObject] {
                    
                    //执行成功的回调
                    finished(result: dict, error: nil)
                    
                    return
                }
                
                //自定义一个网络错误
                //code 一般为负值
                let dataError = NSError(domain: errorDomain, code: -100, userInfo: [NSLocalizedDescriptionKey:"数据饿格式错误"])
                
                finished(result: nil, error: dataError)
                
                
                }) { (_, error) -> Void in
                    
                    //执行错误的回调
                    finished(result: nil, error: error)
                    print(error)
            }
        }
        
    }

}
